<template>
  <div class="background"></div>
  <div class="container">
    <div class="header">
      <img src="../assets/img/logo.webp" class="logo" @click="showPopup" :class="{ flashing: isFlashing }" >
      <img src="../assets/img/mes.jpg" class="mes" @click="showOther">
      <div class="popup" v-if="showPopupMessage" >点击右侧消息，看看其他用户都浏览了什么？</div>
      <div class="search-bar">
        <input type="text" class="search-input" v-model="searchKeyword" @keyup.enter="onSearch">
        <a href="#" class="search-button" @click="onSearch">
          <img src="../assets/img/放大镜.jpg" class="search-icon">
        </a>
      </div>
      <div class="navigation">
        <span @click="Tochat">聊天</span>
        <span @click="Tocart">购物车</span>
        <span @click="Touesr">个人中心</span>
      </div>
    </div>
    <div class="notice">
    {{ currentNotice.text }}
  </div>
    <div class="items-container" v-if="!showsearchresult">
      <div class="item-box" v-for="(item, index) in paginatedItems" :key="index">
        <img :src="item.image" alt="Item Image" class="item-image" @click="buyitem(item)">
        <div class="item-details">
          <h3 class="item-name">{{ item.name }}</h3>
          <p class="item-price">￥{{ item.price }}</p>
        </div>
        
      </div>
    </div>
    <div class="searchresult-container" v-if="showsearchresult">
      <div class="searchresult-box" v-for="(item, index) in paginatedSearchResult" :key="index">
        <img :src="item.image" alt="Item Image" class="item-image">
        <div class="item-details">
          <h3 class="item-name">{{ item.name }}</h3>
          <p class="item-price">￥{{ item.price }}</p>
        </div>
        <button class="buy-button" @click="buyitem(item)">购买</button>
      </div>
    </div>

    <!-- 分页按钮 -->
    <div class="pagination">
      <button @click="prevPage" :disabled="currentPage === 1">上一页</button>
      <span>{{ currentPage }} / {{ maxPage }}</span>
      <button @click="nextPage" :disabled="currentPage === maxPage">下一页</button>
    </div>
  </div>
</template>

<script>
import axios from 'axios';
import { mapState } from 'vuex';
import { globalState } from '../global'; // 引用 globalState

export default {
  name: 'Search',
  data() {
    return {
      searchKeyword: '',
      searchResult: [],
      showsearchresult: false,
      itemsPerPage: 12,
      currentPage: 1,
      isFlashing: false,
      flashingInterval: null,
      showPopupMessage: false,
      notices:[],
      currentNotice: { text: '' },// 假设已通过axios获取
      currentIndex: 0,
      filteredNotices: [],
    };
  },
  methods: {
    Tochat() {
      this.$router.push('/chat');
    },
    Tocart() {
      this.$router.push('/cart');
    },
    Touesr() {
      this.$router.push('/userPage');
    },
    onSearch() {
      this.showsearchresult = true;
      this.searchResult = this.filterItems(this.searchKeyword);
      this.currentPage = 1; // 搜索后重置当前页为第一页
    },
    filterItems(keyword) {
      return this.items.filter(item => {
        return item.name.includes(keyword);
      });
    },
    buyitem(item) {
  // 获取当前时间
  const currentTime = new Date().toISOString();

  // 构造要发送的数据
  const data = {
    username: globalState.username,  // 假设用户名存储在 Vuex 的 state 中
    time: currentTime,
    itemName: item.name
  };

  // 发送 POST 请求给后端
  axios.post('http://localhost:8080/api/products/lookmes', data)
    .then(response => {
      console.log('数据发送成功', response.data);
    })
    .catch(error => {
      console.error('数据发送失败', error);
    });
      this.$router.push({
        name: 'buy',
        params: {
          id: item.id,
        },
      });
    },
    fetchItems() {
      axios.get('http://localhost:8080/api/products/check').then(response => {
        this.$store.dispatch('SetItems', response.data);
      }).catch(error => {
        console.log(error);
      });
    },
    nextPage() {
      if (this.currentPage < this.maxPage) {
        this.currentPage++;
      }
    },
    prevPage() {
      if (this.currentPage > 1) {
        this.currentPage--;
      }
    },
    showPopup() {
      this.showPopupMessage = true;
      setTimeout(() => {
        this.showPopupMessage = false;
      }, 3000);
    },
    showOther() {
  axios.get('http://localhost:8080/api/products/lastSixLooks')
    .then(response => {
      const looks = response.data;
      let message = '最新的六条浏览记录：\n';
      looks.forEach(look => {
        message += `${look.username} 在 ${look.time} 浏览了商品：${look.itemName}\n`;
      });
      alert(message);
    })
    .catch(error => {
      console.error('获取浏览记录失败', error);
      alert('获取浏览记录失败，请稍后再试。');
    });
},
fetchNotices() {
      axios.get('http://localhost:8080/api/notices')
        .then((response) => {
          this.filteredNotices = response.data.filter((notice) => notice.ifplay === 1);
         if (this.filteredNotices.length > 0) {
          this.currentNotice = this.filteredNotices[this.currentIndex];
          this.startCarousel(); // 在数据加载后启动轮播
        }
        })
        .catch((error) => {
          console.error("Error fetching notices:", error);
        });
    },
    startCarousel() {
    if (this.filteredNotices.length > 0) {
      this.carouselInterval = setInterval(() => {
        if (this.currentIndex === this.filteredNotices.length - 1) {
          this.currentIndex = 0;
        } else {
          this.currentIndex++;
        }
        this.currentNotice = this.filteredNotices[this.currentIndex];
      }, 2000);
    }
  },
  },
  computed: {
    ...mapState(['items']),
    maxPage() {
      return Math.ceil(this.items.length / this.itemsPerPage);
    },
    paginatedItems() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      return this.items.slice(startIndex, startIndex + this.itemsPerPage);
    },
    paginatedSearchResult() {
      const startIndex = (this.currentPage - 1) * this.itemsPerPage;
      return this.searchResult.slice(startIndex, startIndex + this.itemsPerPage);
    },
    currentNoticeText() {
      return this.currentNotice ? this.currentNotice.text : '';
    },
},
  created() {
    this.fetchItems();
  },
  mounted() {
    this.flashingInterval = setInterval(() => {
      this.isFlashing = !this.isFlashing;
    }, 1000);
    this.fetchNotices();
  },
  beforeDestroy() {
    clearInterval(this.flashingInterval);
    clearInterval(this.carouselInterval);
  }
};
</script>

<style scoped>
.header {
  width: 95%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 20px;
  position: relative;
}

.logo {
  width: 14%;
  cursor: pointer;
}

.mes {
  width: 4%;  
}

.flashing {
  opacity: 0.5;
}

.popup {
  position: absolute;
  top: 50px;
  left: 100px;
  padding: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  border-radius: 5px;
  z-index: 100;
}

.search-bar {
  display: flex;
  position: relative;
  left: -20px; /* 左移搜索框 */
  background-color: #74a12a;
  border-radius: 25px;
  padding: 5px 10px; /* 调整内边距 */
  width: 30%; /* 调整搜索框宽度 */
}

.search-input {
  border: none;
  padding: 8px; /* 增加输入框的内边距 */
  font-size: 16px; /* 调整字体大小 */
  border-radius: 25px;
  width: 100%;
}

.search-button {
  cursor: pointer;
  margin-left: 10px;
}

.search-icon {
  width: 35px;
  height: 35px;
  border-radius: 50%;
}

.navigation {
  display: flex;
  gap: 20px; /* 调整间距 */
  font-size: 30px;
}

.navigation span {
  cursor: pointer;
  transition: color 0.3s;
  color: #ae08cf; /* 初始颜色 */
}

.navigation span:hover {
  color: red;
}

.items-container, .searchresult-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 20px;
}

.item-box, .searchresult-box {
  width: calc(25% - 10px);
  box-sizing: border-box;
  border: 2px solid skyblue;
  display: flex;
  flex-direction: column;
  padding: 10px;
  border-radius: 10px;
}

.item-image {
  width: 100%;
  height: 250px; /* 增加图片高度 */
  object-fit: cover;
  cursor: pointer;
  border-radius: 20px; /* 设置圆角半径，15px可以根据需要调整 */
}

.item-details {
  text-align: center; /* 中心对齐 */
  padding: 10px 0;
}

.item-name {
  margin: 0;
  font-size: 18px;
}

.item-price {
  font-weight: bold;
  color:rgb(248, 109, 132);
  font-size: 30px;
}

.buy-button {
  align-self: center;
  padding: 10px 20px; /* 增加按钮大小 */
  border: none;
  background-color: #74a12a;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  font-size: 18px; /* 增加字体大小 */
}

.buy-button:hover {
  background-color: #55881a;
}

.container {
  width: 100%;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  background-image: url('../assets/img/mainpage.jpg');
  background-size: cover;
  background-position: center;
  background-color: rgba(41, 18, 192, 0.5); /* 设置背景颜色的透明度 */
  opacity: 0.95;
}
.background {
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  background-image: url('../assets/img/mainpage.jpg');
  background-size: cover;
  background-position: center;
  z-index: -1;
}

.pagination {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 20px;
}

.pagination button {
  padding: 10px 20px;
  border: none;
  background-color: #74a12a;
  color: white;
  border-radius: 5px;
  cursor: pointer;
  font-size: 18px;
}

.pagination button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.pagination span {
  font-size: 18px;
  line-height: 36px; /* 保持和按钮高度一致 */
}
notice-container {
  position: relative;
  width: 100%;
 
}

.notice {
  color: red;
  font-size: 24px;
  text-align: center;
}

</style>
